let observers = {};
function observe(name, key, callback) {
    const index = observers[name].findIndex(vo => vo.key === key);
    if (index >= 0) {
        observers[name][index] = {
            key,
            callback
        }
    } else {
        observers[name].push({
            key,
            callback
        });
    }
}

function unobserve(name, key) {
    const index = observers[name].findIndex(vo => vo.key === key);
    (index >= 0) && observers[name].splice(index, 1);
}

function watch(name, obj) {
    observers[name] = [];
    obj = new Proxy(obj, {
       get(target, key) {
           if (target[key] === undefined) {
               return {};
           }
           return target[key];
       },
        set(target, key, value, receiver) {
           for (let i = 0; i < observers[name].length; i++) {
               observers[name][i].callback
               && observers[name][i].callback(observers[name][i].key, key, value);
           }
           return Reflect.set(target, key, value, receiver)
        }

    });
    return obj;
}


export function injectObserver(XUE) {
    XUE.observer = {
        observe,
        unobserve,
        watch
    };
}
